﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace MaxZhang.EasyEntities.EasyDesigner.Core
{
    public static class ObjectHelper
    {

        /// <summary>
        /// 将对象序列化成字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>字符串</returns>
        public static string Serializer(this object obj)
        {
            return funSerializerToXml(obj,"x","");
        }

        /// <summary>
        /// 将字符串反序列化为对象
        /// </summary>
        /// <typeparam name="TType">对象类型</typeparam>
        /// <param name="strXml">字符串</param>
        /// <returns>TType类型的对象</returns>
        public static TType Deserialize<TType>(this string strXml)
        {
            return (TType)(funDeserializeToXml(strXml, typeof(TType)));
        }



        /// <summary>
        /// 序列化obj
        /// </summary>
        /// <param name="tcpref"></param>
        /// <returns></returns>

        public static string funSerializerToXml(object obj, string xsi, string xsd)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                //SoapFormatter formatter = new SoapFormatter();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                xsn.Add(xsi, xsd);


                using (TextWriter tw = new StringWriter(sb))
                {
                    serializer.Serialize(tw, obj);
                }
            }
            catch
            {
            }

            //string str = sb.ToString();
            return sb.ToString();
        }

       

        /// <summary>
        /// 反序列化obj
        /// </summary>
        /// <param name="strMsg"></param>
        /// <returns></returns>
        public static object funDeserializeToXml(string strXML, Type type)
        {
            object obj = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(type);
                using (StringReader sr = new StringReader(strXML))
                {
                    obj = serializer.Deserialize((TextReader)sr);
                }
            }
            catch
            { }
            return obj;
        }
    }
}
